import {useEffect, useMemo, useState} from 'react';
import { Switch, Route, useParams, useRouteMatch } from "react-router-dom";
import { Link, Redirect } from './Router'
import { useIntl } from 'react-intl';
import { useTokenGraph } from './TokenGraph';
import Add from './Add'
import Remove from './Remove'
import * as Mui from '@material-ui/core';
import useContractChecker from './useContractChecker';
import { useTokenSelectionDispatch } from './TokenSelection';
import '../styles/custom.css'
import setting from "../assets/images/setting.png";
import ht from "../assets/images/ht.png";
import swapTrans from "../assets/swap.svg";
import add from '../assets/images/add.png'

function LiquidityItem({ address }) {
  const tokenGraph = useTokenGraph()
  const pair = useMemo(() => {
    const result = { ...tokenGraph.pairs[address] }
    result.token0 = { ...tokenGraph.tokens[result.token0], address: result.token0 }
    result.token1 = { ...tokenGraph.tokens[result.token1], address: result.token1 }
    return result
  }, [tokenGraph, address])
  const balance = useContractChecker({
    type: 'balance',
    id: address,
    decimals: pair.decimals
  })
  return balance > 0 && (
    <Mui.ListItem component={Link} key={address} button to={`/liquidity/${address}`}>
      <Mui.ListItemText
        primary={`${pair.token0.displayName}/${pair.token1.displayName}`}
        secondary={balance.toFixed()}
        primaryTypographyProps={{ noWrap: true }}
        secondaryTypographyProps={{ noWrap: true }}
      />
    </Mui.ListItem>
  )
}

function MyLiquidity() {
  const tokenGraph = useTokenGraph()
  const intl = useIntl()

  return (
    <>
      <Mui.DialogTitle disableTypography>
        <Mui.Grid container justifyContent="space-between" alignItems="center">
          <Mui.Grid item>
            <Mui.Typography gutterBottom variant="h5" component="div">
              {intl.formatMessage({ defaultMessage: 'My Liquidity' })}
            </Mui.Typography>
          </Mui.Grid>
          <Mui.Grid item>
            <Mui.Button className='cn-custom-btn' component={Link} variant="outlined" size="small" to="/liquidity/add">
              {intl.formatMessage({ defaultMessage: 'Add Liquidity' })}
            </Mui.Button>
          </Mui.Grid>
        </Mui.Grid>
      </Mui.DialogTitle>
      <Mui.DialogContent sx={{ p: 0 }}>
        <Mui.List sx={{ px: 1 }}>
          {Object.keys(tokenGraph.pairs).map((address) => <LiquidityItem key={address} address={address} />)}
        </Mui.List>
      </Mui.DialogContent>
    </>
  )
}

function InnerRemove() {
  const tokenGraph = useTokenGraph()
  const { address } = useParams();

  return tokenGraph.pairsLength ?
    (address in tokenGraph.pairs ? <Remove address={address} /> : <Redirect to="/liquidity" />)
    : <Mui.Grid container p={3} justifyContent="center" alignItems="center">
      <Mui.Grid item>
        <Mui.CircularProgress />
      </Mui.Grid>
    </Mui.Grid>
}

function RedirectToAdd() {
  const tokenGraph = useTokenGraph()
  const tokenSelectionDispatch = useTokenSelectionDispatch()
  const { address } = useParams();

  useEffect(() => {
    if (address in tokenGraph.pairs) {
      const address0 = tokenGraph.pairs[address].token0
      const address1 = tokenGraph.pairs[address].token1
      tokenSelectionDispatch({ type: 'set_token', isToken0: true })
      tokenSelectionDispatch({ type: 'select', token: { ...tokenGraph.tokens[address0], address: address0 } })
      tokenSelectionDispatch({ type: 'set_token', isToken0: false })
      tokenSelectionDispatch({ type: 'select', token: { ...tokenGraph.tokens[address1], address: address1 } })
    }
  }, [address, tokenGraph, tokenSelectionDispatch])

  return tokenGraph.pairsLength ? <Redirect to="/liquidity/add" /> : undefined
}

export default function Liquidity() {
  const { path, isExact } = useRouteMatch();

  const [selectTab, setSelectTab] = useState(0)

  const handleChange = (event, newValue) => {
    setSelectTab(newValue);
  };

  return (
    <Mui.Container style={{height: '100%', paddingBottom: 94, maxWidth: 'initial'}} sx={{overflow: 'hidden', paddingX: {xs: 2, sm: 12.5}}}>
      {/*<Mui.Grid container spacing={3} p={3}>*/}
      {/*  <Mui.Grid item width="100%" lg={6} display={{ xs: isExact ? 'block' : 'none', lg: 'block' }}>*/}
      {/*    <Mui.Paper sx={{ maxWidth: 500, mx: 'auto' }}>*/}
      {/*      <MyLiquidity />*/}
      {/*    </Mui.Paper>*/}
      {/*  </Mui.Grid>*/}
      {/*  <Switch>*/}
      {/*    <Route path={`${path}/add/:address`}>*/}
      {/*      <RedirectToAdd />*/}
      {/*    </Route>*/}
      {/*    <Route path={`${path}/add`}>*/}
      {/*      <Mui.Grid item width="100%" lg={6}>*/}
      {/*        <Mui.Paper sx={{ maxWidth: 500, mx: 'auto' }}>*/}
      {/*          <Add />*/}
      {/*        </Mui.Paper>*/}
      {/*      </Mui.Grid>*/}
      {/*    </Route>*/}
      {/*    <Route path={`${path}/:address`}>*/}
      {/*      <Mui.Grid item width="100%" lg={6}>*/}
      {/*        <Mui.Paper sx={{ maxWidth: 500, mx: 'auto' }}>*/}
      {/*          <InnerRemove />*/}
      {/*        </Mui.Paper>*/}
      {/*      </Mui.Grid>*/}
      {/*    </Route>*/}
      {/*  </Switch>*/}
      {/*</Mui.Grid>*/}
      <Mui.Box sx={{ height: {xs: 'auto', sm: '100%'}, width: '100%', backgroundColor: 'white', borderRadius: 3, paddingTop: 3, paddingBottom: 2}}>
        <Mui.Box style={{display: 'flex', alignItems: 'center'}} sx={{paddingX: {xs: 2, sm: 3.75}}}>
          <Mui.Box className="blue-point"></Mui.Box>
          <Mui.Box style={{fontSize: 20, fontWeight: 500}}>
            Swap
          </Mui.Box>
          <Mui.Box style={{height: 38, marginLeft: 'auto'}}>
            <img src={setting} alt=""/>
          </Mui.Box>
        </Mui.Box>


        <Mui.Box sx={{minWidth: {sm: 468}, width: {sm: '46.8%'}}} style={{textAlign: 'center', backgroundColor: '#F4F4F6', height: 528, margin: 'auto', marginTop: 80, borderRadius: 12, padding: 30}}>

          <Mui.Paper square style={{backgroundColor: '#F4F4F6', boxShadow: 'none'}}>
            <Mui.Tabs
                value={selectTab}
                indicatorColor="secondary"
                // textColor="black"
                onChange={handleChange}
                variant="fullWidth"
                centered
                // aria-label="disabled tabs example"
                aria-label="simple tabs example"
            >
              <Mui.Tab label="Your Liquidity" />
              <Mui.Tab label="Add Liquidity" />
            </Mui.Tabs>
          </Mui.Paper>
          {selectTab === 0 && <Mui.Box>
            <Mui.Box className="pool-content" style={{paddingTop: 79}}>Connect to a wallet to view your liquidity.</Mui.Box>
            <Mui.Box className="display-flex" style={{ alignItems: "center", justifyContent: 'center', paddingTop: 60}}>
              <Mui.Box className="pool-content-join">Don't see a pool you joined? </Mui.Box>
              <Mui.Box>Import it</Mui.Box>
            </Mui.Box>

          </Mui.Box>}

          {selectTab === 1 && <Mui.Box>
            <Mui.Box className="display-flex swap-title" style={{paddingTop: 30}}>
              <Mui.Box>Input</Mui.Box>
              <Mui.Box style={{marginLeft: 'auto'}}>Balance: 1.00626</Mui.Box>
            </Mui.Box>
            <Mui.Box className="display-flex" style={{alignItems: 'center', backgroundColor: 'white', borderRadius: 12}} sx={{height: 76}}>
              <Mui.OutlinedInput
                  id="outlined-adornment-weight"
                  // value={values.weight}
                  // onChange={handleChange('weight')}
                  aria-describedby="outlined-weight-helper-text"
                  inputProps={{
                    'aria-label': 'weight',
                  }}
                  placeholder={0.0}
                  labelWidth={0}
              />
              <Mui.Box className="max-btn">MAX</Mui.Box>
              <img src={ht} className="swap-img" alt=""/>
              <Mui.Select
                  native
                  value="ht"
                  // onChange={handleChange}
                  inputProps={{
                    name: 'age',
                    id: 'age-native-simple',
                  }}
                  classes={{outlined: {border: 'none'}}}
                  sx={{border: 'none'}}
              >
                <option aria-label="None" value="" />
                <option value="ht">HT</option>
                <option value="vit">VIT</option>
              </Mui.Select>
            </Mui.Box>
            <img src={add} style={{marginTop: 40, marginBottom: 4}} className="swap-img" alt=""/>

            <Mui.Box className="display-flex swap-title" style={{}}>
              <Mui.Box>Input</Mui.Box>
              <Mui.Box style={{marginLeft: 'auto'}}>Balance: 1.00626</Mui.Box>
            </Mui.Box>
            <Mui.Box className="display-flex" style={{alignItems: 'center', backgroundColor: 'white', borderRadius: 12}} sx={{height: 76}}>
              <Mui.OutlinedInput
                  id="outlined-adornment-weight"
                  // value={values.weight}
                  // onChange={handleChange('weight')}
                  aria-describedby="outlined-weight-helper-text"
                  inputProps={{
                    'aria-label': 'weight',
                  }}
                  placeholder={0.0}
                  labelWidth={0}
              />
              <Mui.Box className="max-btn" style={{}}>MAX</Mui.Box>
              <img src={ht} className="swap-img" alt=""/>
              <Mui.Select
                  native
                  value="ht"
                  // onChange={handleChange}
                  inputProps={{
                    name: 'age',
                    id: 'age-native-simple',
                  }}
                  classes={{outlined: {border: 'none'}}}
                  sx={{border: 'none'}}
              >
                <option aria-label="None" value="" />
                <option value="ht">HT</option>
                <option value="vit">VIT</option>
              </Mui.Select>
            </Mui.Box>
            <Mui.Box className="display-flex swap-title" style={{paddingTop: 40, opacity: 1}}>
              <Mui.Box className="font-14">Prices and pool share</Mui.Box>
              {/*<Mui.Box style={{marginLeft: 'auto'}}>-</Mui.Box>*/}
            </Mui.Box>
            {/*<Mui.Button variant="contained" color="secondary" style={{width: '100%', height: 60, background: "#ED1F7A"}}>*/}
            {/*  Add*/}
            {/*</Mui.Button>*/}
          </Mui.Box>}
        </Mui.Box>
      </Mui.Box>
    </Mui.Container>
  )
}